package com.spica.spicaschool.ui.circle

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.drakeet.multitype.ItemViewDelegate
import com.spica.spicaschool.R
import com.spica.spicaschool.bean.diary.Diary
import com.spica.spicaschool.utils.toUid
import com.spica.spicaschool.view.ItemDiary
import org.ocpsoft.prettytime.PrettyTime
import java.text.SimpleDateFormat
import java.util.*

class DiaryItemDelegate2 constructor(private val activity: Activity) :
    ItemViewDelegate<Diary, DiaryItemDelegate2.ViewHolder>() {


    private val prettyTime = PrettyTime(Locale.CHINA)

    override fun getItemId(item: Diary): Long = item.diaryUid.toUid().toLong()

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, item: Diary) {
        val isLike = item.isLike
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
        val date = sdf.parse(item.diaryTime)

        // UI填充
        with(holder.view) {
            avatar.load(R.drawable.default_head) {
                placeholder(R.drawable.default_head)
                error(R.drawable.default_head)
            }
            author.text = item.user.uNickname
            pushType.text = "${item.user.uRank}级 发布动态"
            info.text = item.diaryContentPreview
            timeView.text = prettyTime.format(date)
            title.text = item.diaryTitle
            likeNum.text = "${item.diaryLikeNum}"
            replyNum.text = "${item.diaryCommentNum}"
            if (isLike == 1) btnLike.load(R.drawable.ic_like_selected)
            // 点击查看详情
            setOnClickListener {
                val navController =
                    Navigation.findNavController(activity, R.id.fragment_container_view)
                val bundle = bundleOf(Pair("DiaryId", item.diaryId))
                navController.navigate(R.id.action_home_to_diary_see, bundle)
            }
            btnLike.setOnClickListener {
                when (isLike) {
                    0 -> {
                        // likeAnim.show()
                        holder.view.btnLike.load(R.drawable.ic_like_selected)
                    }
                    else -> {
                        // unlikeAnim.show()
                        holder.view.btnLike.load(R.drawable.ic_like_normal)
                    }
                }
            }
        }
    }

    override fun onCreateViewHolder(
        context: Context,
        parent: ViewGroup
    ): ViewHolder {
        return ViewHolder(ItemDiary(context))
    }

    // 视图绑定
    class ViewHolder(val view: ItemDiary) : RecyclerView.ViewHolder(view)
}
